import { Modal, UploadFile, UploadProps, message } from "antd";
import { uploadFilesPropsTypes } from "./type";
import { InboxOutlined } from "@ant-design/icons";
import Dragger from "antd/es/upload/Dragger";
import { useEffect, useState } from "react";
import { uploadfile, API } from "@/api/uploadfiles"
import { cloneDeep } from "lodash";
interface slefUploadFile extends UploadFile {
  file?: any
  key?: string
}
let fileData: any = {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
let fileNowList: slefUploadFile[] = []
const UploadFiles: React.FC<uploadFilesPropsTypes> = (props) => {
  const [fileList, setFileList] = useState<slefUploadFile[]>([
  ])

  const handelsetLise = (list: slefUploadFile[]) => {
    fileNowList = list
    return new Promise((resolve) => {
      setFileList(cloneDeep(list))
      resolve("")
    })
  }
  useEffect(() => {
    setFileList([])
  }, [])
  const handleOk = async () => {
    const nowfiles = fileNowList.filter(e => !e.url)
    if (nowfiles.length === 0) {
      message.error("请选择文件")
      return
    }
    for (let index = 0; index < nowfiles.length; index++) {
      const element = nowfiles[index];
      element.status = "uploading"
    }
    await handelsetLise(fileNowList)
    nowfiles.map(e => {
      async function uploadEvent(progressEvent: { loaded: number; total: number; }) {
        const progressPercent = Number(
          ((progressEvent.loaded / progressEvent.total) * 100).toFixed(2)
        );
        const cuFile = nowfiles.find(ele => ele.uid === e.uid)
        if (cuFile) {
          cuFile.percent = progressPercent >= 90 ? 90 : progressPercent
          handelsetLise(fileNowList)
        }
      }
      const config = {
        onUploadProgress: uploadEvent
      }
      const formData = new FormData();
      formData.append('file', fileData[e.uid]);
      uploadfile(formData, config).then(res => {
        const obj = { uid: e.uid, key: res, type: true }
        changeStatus(obj)
      }).catch(() => {
        const obj = { uid: e.uid, type: false }
        changeStatus(obj)
      })

    })



  }
  const changeStatus = (element: any) => {
    setTimeout(() => {
      const res = fileNowList.find(e => e.uid === element.uid)
      if (res && element.type) {
        res.key = element.key
        res.url = `${API.GetFile}?fileKey=${res.key}`
        if (res.percent === 90) {
          res.status = "done"
          res.percent = 100
        }
      } else if (res && !element.type) {
        if (res.percent === 90) {
          res.status = "error"
          res.percent = 0
        }
      }
      handelsetLise(fileNowList)
    }, 0);
  }
  const handleCancel = () => {
    close()
  }
  const close = () => {
    let loadList = false
    if (fileList.length > 0) {
      loadList = true
    }
    props.changeShow(false, loadList)
    fileData = {}
    setFileList([])
  }

  const Draggerprops: UploadProps = {
    name: 'file',
    multiple: true,
    action: '',
    onChange() {
    },
    customRequest(e: any) {
      const { onSuccess, file } = e
      const f: slefUploadFile = {
        uid: file.uid,
        name: file.name,
        status: "done",
        percent: 0,

        // file: file
      }
      fileData[f.uid] = file
      handelsetLise([...fileNowList, f])

      onSuccess({}, file)
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
    showUploadList: {
      showDownloadIcon: false,
      showRemoveIcon: false,
    },
  };
  return (
    <Modal title="上传文件" open={props.show} onOk={handleOk} onCancel={handleCancel}>
      <Dragger {...Draggerprops} fileList={fileList}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或者拖拽上传文件</p>
        <p className="ant-upload-hint">
          Support for a single or bulk upload. Strictly prohibited from uploading company data or other
          banned files.
        </p>
      </Dragger>
    </Modal>
  )
}
export default UploadFiles